<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/13/013
 * Time: 10:28
 */

namespace app\index\controller;


use app\common\controller\Frontend;
use app\common\model\Useraddress;
use think\response\Json;

class Address extends Frontend
{
    protected $noNeedRight = ['*'];
    //地址列表
    public function index(){
        $result = Useraddress::all(['user_id' => $this->auth->id]);
        return json($result);
    }
    //增加地址
    public function add(){
        if($this->request->isPost()){
            $params = $this->request->post("row/a");
            if($params) {
                $address = new Useraddress;
                $result = $address->validate([
                    'name' => 'require',
                    'user_id' => 'require'
                ])->save([
                    'name' => $this->request->post('row[name]'),
                    'user_id' => $this->auth->id]);
                if ($result) {
                    echo '新增成功';
                    return;
                }
                $this->error($address->getError());
            }
        }
        echo '增加地址';
    }
    //修改地址
    public function edit(){
        if($this->request->isPost()){
            $params = $this->request->post("row/a");
            if($params){
                $address = new Useraddress();
                $result = $address->allowField(true)->save($_POST,['id'=>$this->request->post('row[id]')]);
                if($result){
                    echo '修改成功';
                    return;
                }
                echo '修改失败';
            }
        }
        echo '修改地址';
    }
    //删除地址
    public function del(){
        if($this->request->isPost()){
            $params = $this->request->post("row/a");
            if($params) {
                $id = $this->request->post('row[id]');
                $result = Useraddress::destroy($id);
                if($result){
                    echo '删除成功';
                    return;
                }
                echo '删除失败';
            }
        }
        echo '删除地址';
    }
}